import axios from 'axios';
import qs from 'qs';

axios.defaults.timeout = 10000;

// export var baseUrl = "https://www.starnests.com/php/admin.php";
export var baseUrl = "/php";  // 开发

axios.defaults.baseURL = baseUrl;
axios.interceptors.request.use(
  config => {

    return config;
  },
  error => {
    return Promise.reject(err);
  }
);
axios.interceptors.request.use(
  req => {
    if (req.method === 'post') {
      req.data = qs.stringify(req.data);
    }
    return req;
  },
  error => Promise.reject(error)
);


/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function fetch(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.defaults.timeout = 10000;
    axios
      .get(url, {
        params: params,
      })
      .then(response => {
        resolve(response.data);
        // if (response.data.code === "403") {
        //   this.$router.push({path: "/"});
        // }
      })
      .catch(err => {
        reject(err);
      });
  });
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post(url, data) {
  console.log(url, data);
  return new Promise((resolve, reject) => {
    axios.defaults.timeout = 10000;
    axios.post(url, data).then(
      response => {
        resolve(response.data);
        // if (response.data.code === "403") {
        //   this.$router.push({path: "/"});
        // }
      },
      err => {
        reject(err);
      }
    );
  });
}

export function upload(url, param) {
  return new Promise((resolve, reject) => {
    axios.defaults.timeout = 100000;
    let config = {
      headers: {
        "Content-Type": "multipart/form-data"
      }
    };
    const instance = axios.create({
      withCredentials: true
    })
    instance.post(url, param, config).then(
      response => {
        resolve(response.data);
      },
      err => {
        reject(err);
      }
    );
  });
}


